/*
 * dajare-cloud
 */
(function($, window){
	String.prototype.replaceAll = function(a, b){return this.split(a).join(b);}
	/* DajareCloud API TEST
	 * http://dajare1242.appspot.com/test/
	 */
	/* Global Variable Start */
	var jQDajareCloudValue = {find:{},rank:{normal:{},withText:{}},ti:{},api:{}},
	jQDajareCloudSelector = {
		"jQDajareCloud":"#jQDajareCloud",
		"jQDajareCloudHeader":"#jQDajareCloudHeader",
		"jQDajareCloudLogoArea":"#jQDajareCloudLogoArea",
		"jQDajareCloudUtility":"#jQDajareCloudUtility",
		"jQDajareCloudButton":"#jQDajareCloudButton",
		"jQDajareCloudGrid":"#jQDajareCloudGrid",
		"jQDajareCloudFooter":"#jQDajareCloudFooter",
		"jQDajareCloudContentFooter":"#jQDajareCloudContentFooter"
	};
	/* Dajare Cloud API */
	jQDajareCloudValue.api={
			find:"http://dajare1242-alpha.appspot.com/api/dajare/find?callback=?",
			pc:"http://dajare1242-alpha.appspot.com/api/user/dajare/ranking/app10/weekly/json/pc?callback=?",
			ti:"http://dajare1242-alpha.appspot.com/api/user/dajare/ranking/app10/weekly/json/ti?callback=?"
	}
	/* new server */
	jQDajareCloudValue.api={find:"http://dajare-api.appspot.com/find/?callback=?"}
	if(typeof window.jQDajareCloudValue == "undefined") window.jQDajareCloudValue = $.jQDajareCloudValue = jQDajareCloudValue;
	/* Global Variable End */
	/*******************/
	/* Request Start  */
	/******************/
	/* Find Objects */
	// http://http://dajare-api.appspot.com/?page=1&size=20
	// http://http://dajare-api.appspot.com/?keyword=検索文字列&page=ページ&size=1ページの件数
	/* GAE DataStore API
	 * GAE/Pへ移行する際の注意点
	 * PaaSの限界に挑戦。
	 */
	/* jQDajareCloudValue.api.find "page":1, "size":1 */
	function dajareWrite(d){
		var dt=[],BreakPoint="<br>\n";
		console.log(d.results[0]);
		for (i in d.results){
			// つぶやき結果
			dt.push([]);
			var line = d.results[i];
			// console.log((dt.length-1));
			for (k in line){
				if(k=="createDate"){
					var dates = new Date(line.createDate),dateStr=dates.getFullYear()+"年"+(dates.getMonth()+1)+"月"+dates.getDate()+'日';
					// console.log(dates.getFullYear(),dates.getMonth()+1,dates.getDate())
					line[k]=dateStr;
				}
				if(k=="createDate" || k=="text"){
					dt[dt.length-1].push(line[k]);
				}
			}
		}
		for (i in dt){
			$("#daj").append('<div class="csvDajare">'+dt[i].join(",")+BreakPoint+"</div>");
		}
		// $(".csvDajare").hide();
		// $(".csvDajare").fadeIn(3000);
	}
	$(
			function(){
				var b = document.body;
				$(b).append('<div id="loader"><img src="http://dajare-mockup.appspot.com/lib/images/loader.gif" alt="読み込み中..."></div>');
				$("#loader").css({
					"position":"absolute",
					"left":($(document).width()-30)/2,
					"top":300
				});
				/*
				 * header : logo, tweet btn,follow btn,tweet all counts
				 * body : search panel, search result, 
				 * <!-- html5:header -->
				 * <div id="header">
				 * 		<div id="logo"></div>
				 * 		<div class="utility">
				 * 			<div id="totalDajare">クロール済み(ダジャレクローラ)ダジャレ総数<span id="DajareNum"></span>件</div>
				 * 		</div>
				 * </div>
				 * <!-- / html5:header -->
				 */
				var c='<div id="wrapper" class="container"></div>',
				gh='<div id="global_header" class="global_menu"><div class="gm_left"><ul><li class="dajareInfo"><a href="javascript:void(0);">ダジャレクラウドから皆様へ</a></li><li><a href="javascript:void(0);" class="dajareAPI">ダジャレクラウド&nbsp;API</a></li><li><a href="javascript:void(0);" class="dajareFeedBack">お問い合わせ</a></li></ul></div><div class="gm_right"><ul><li><a href="javascript:void(0);" class="dajareLogin">Sign in with Twitter</a></li></ul></div><br clear="all"></div>',// Global Header
				h='<div id="header"><br clear="all"></div>',
				footer='<div id="footer"></div>',
				total='<div id="totalDajare" class="utilityPanel">Crawler：<span id="DajareNum"></span>件</div>',
				f='<div id="searchResultPanel"><form onsubmit="return false;" name="dajareSearch"><div class="searchTitle">ダジャレ・リサーチ</div><input name="search" id="dse"><input type="button" value="検索" id="dsesubmit"></form></div>',
				l='<div id="logo"><a href="/"><img src="http://dajare-mockup.appspot.com/lib/images/logo_alpha.png"></a></div><div id="utility"></div>',
				tw_follow='<div id="custom-tw_follow"><a href="javascript:void(0);" title="ダジャレクラウドをフォローしましょう！"></a></div>';
				tw_btn='<div id="custom-tw_share"><a href="javascript:void(0);" title="ダジャレクラウドでボケましょう！"></a></div>',
				comment='<div class="comment">ダジャレクラウドへの参加は、<a href="javascript:void(0);" class="bokeBtn" title="ダジャレクラウドでボケましょう！"><span class="red">ボケる</span>ボタン</a>をクリック!</div>';
				
				$(b).append(c);
				$("#wrapper").append(gh+h);// Header要素の代入(空)
				$("#header").prepend(l);
				$("#utility").append(total+'<div id="dajareTweet" class="utilityPanel">'+tw_btn+tw_follow+comment+'<br clear="all">'+'</div>');
				$("#wrapper").append(f);
				$("#screen-name").css({"display":"none"});
				/* Tweet Btn & Follow Click Start */
				$("#custom-tw_share a,a.bokeBtn").click(function(){
					var w=480,h=320,x=(window.screen.width-w)/2,y=(window.screen.height-h)/2,
					shareUrl = 'https://twitter.com/share?url=https%3A%2F%2Fdajare1242.appspot.com%2F&text=%23dajare';
					window.open(shareUrl,"BokeruWindow","width="+w+",height="+h+",screenX="+x+",screenY="+y);
				});
				$("#custom-tw_follow a").click(function(){
					var w=480,h=620,x=(window.screen.width-w)/2,y=(window.screen.height-h)/2,
					followUrl = 'https://twitter.com/intent/user?original_referer='+location.href+'&region=following&screen_name=dajare1242&source=followbutton&variant=1.1';
					window.open(followUrl,"FollowWindow","width="+w+",height="+h+",screenX="+x+",screenY="+y);
				});
				/* Tweet Btn & Follow Click End */
				//http://www.ohfuji.name/dajare/apicall.html
				$(".dajareAPI").click(function(){
					// $(this).colorbox({href:'http://www.ohfuji.name/dajare/apicall.html',width:800,height:600,iframe:true});
					//$(this).colorbox({href:'/manual',width:800,height:600,iframe:true});
				});
				$(".dajareInfo,.dajareAPI").hide();//
				$(".dajareFeedBack").click(function(){
					var m = 'http://dajare-mockup.appspot.com/mail';//http://dajare-mockup.appspot.com
					$(this).colorbox({href:m, width:800, height:600, iframe:true});
				});
				$(".dajareLogin").click(function(){
					var str = "現在開発中のため間実装されていない機能があります。ご了承ください。";
					alert(str);
				});
				$("#dsesubmit").click(
						function(){
							$("#daj").html("");
							$("#loader").show();
							var w=$("#dse").val(),dt=[],BreakPoint="<br>\n";;
							if(w==""){
								alert("検索ワードををいれてみて！");
								return;
							}
							param.data.page=1,param.data.keyword=w,param.data.size=100,BreakPoint="<br>\n";
							// searchResultPanel
							param.success=function(d){
								$("#loader").fadeOut();
								if(d.allTotal==0){
									alert("他の検索ワードををいれてみてね！");
									return;
								}
								$("#daj").html("");
								/* http://www.google.co.jp/search?q=[:word]&ie=utf-8&oe=utf-8&aq=t&hl=ja */
								var srp = '<div id="dseResult"><div class="searchResultTitle"><span class="word"><a href="http://www.google.co.jp/search?q='+$("#dse").val()+'&ie=utf-8&oe=utf-8&aq=t&hl=ja">'+$("#dse").val()+'</a></span>での検索結果&thinsp;<span class="resultNum">'+d.allTotal+'</span>件</div>',
								backTo='<div id="dseReloads"><a href="javascript:void(0);" onclick="location.reload()">もどる</a></div>';
								if(d.total < param.data.size) d.total = param.data.size;
								p=d.allTotal / d.total;
								srp+='<ul>';
								var count=0;
								for(var i=0;i<p;i++){count=i+1,srp+='<li><a href="javascript:void(0);" data-count="'+count+'">'+count+'</a></li>';}
								srp+='</ul><br clear="all">';//件数表示
								srp+='</div>';
								$("#dseResult,#dseReloads").remove();
								$("#searchResultPanel").append(srp+backTo);
								if(count==1){
									$("#dseResult ul,#dseResult br").css({display:"none"})
								}
								$("div.searchResultTitle span.word a").click(function(){
									$(this).colorbox({width:"90%",height:"90%",iframe:true});
								});
								$("#searchResultPanel ul li a").click(function(){
									$("#daj").html("");
									$("#loader").show();
									param.data.page=$(this).attr("data-count");
									$.ajax(param);
								});
								dajareWrite(d);
							}
							$.ajax(param);
							clearInterval(interval);
						}
				);
				
			}
	);
	
	var param = {url:jQDajareCloudValue.api.find, data:{"page":1, "size":15},dataType:"jsonp",
			success:function(d){
			/* jsonp */
			$("#loader").fadeOut();
			window.jQDajareCloudValue.find=d;
			$(
					function(){
						var b = document.body;
						if($("#daj").size()==0) $("#wrapper").append('<div id="daj"></div>');
						if(window.jQDajareCloudValue.find.allTotal==0){
							clearInterval(interval);
						}
						$("#DajareNum").html(window.jQDajareCloudValue.find.allTotal);
						dajareWrite(window.jQDajareCloudValue.find);
					}
			);
		}
		};
	$.ajax(param);
	count = param.data.page;
	var interval = setInterval(function(){
		++count;
		param.data.page = count;
		$.ajax(param);
	}, 3000);
	/* すべての非同期処理が終わった後に処理。 */
	
	/* Ranking Objects - Normal */
	/* Request End */
	/* jQuery Sub Class @ Dajare Cloud */
	var jQDajareCloud = window.jQDajareCloud = $.jQDajareCloud = function(vars){
		return jQDajareCloud.prototype.init(vars);
	}
	jQDajareCloud.prototype = {
		s:{// Selector Name : Get & Add
			get:function(){return jQDajareCloudSelector;},
			add:function(k){
				if(typeof k=="undefined") return jQDajareCloudSelector;
				var cs=".",ci="#",v=k.replace(cs, ""),v=k.replace(ci, "");
				return jQDajareCloudSelector[v] = k;
			}
		},
		v:function(){// Global Value
			return window.jQDajareCloudValue;
		},
		ct:{//Content Tables
			// support:[2,"jQDajare1242Support",{title:"ダジャレ サポータ"}],
			find:[1,"jQDajare1242find",{title:"ダジャレクローラ"}],
			// api:[2,"jQDajare1242API",{title:"ダジャレクラウドAPI"}],
			// rank:[2,"jQDajare1242Rank",{title:"ダジャレランキング"}],
			license:[2,"jQDajare1242License",{title:"ライセンスについて"}],
			backup:[2,"jQDajare1242Backup",{title:"応援"}]
		},
		init : function(){
			var a = this.s.get();
			$(function(){
				var b = document.body;
				$(b).append('<div id="'+a.jQDajareCloud.replace("#", "")+'">'+
				'<div id="'+a.jQDajareCloudHeader.replace("#", "")+'">'+
					'<div id="'+a.jQDajareCloudLogoArea.replace("#", "")+'"></div>'+
					'<div id="'+a.jQDajareCloudUtility.replace("#", "")+'"></div>'+
					'<div id="'+a.jQDajareCloudButton.replace("#", "")+'"></div>'+
				'</div>'+
				'<div id="'+a.jQDajareCloudGrid.replace("#", "")+'"></div>'+
				// '<div id="'+a.jQDajareCloudFooter.replace("#", "")+'"></div>'+
				'<div id="'+a.jQDajareCloudContentFooter.replace("#", "")+'"></div>'+
				'</div>');
			});
			return this;
		},
		createGrid:function(num, id, obj){
			if(typeof id=="undefined" || id=="") return 0;
			if(typeof num=="undefined" || num=="") num=2;
			var columnName = 'jQDCG'+num+'Column';
			var a=this.s.get(),b=arguments[1],s='<div class="'+columnName+'" id="'+id+'"><div class="columnTitle"><div class="columnTitleIcon"></div><div class="columnTitleText"><h3></h3></div><br clear="all"></div><div class="columnDescription"><div class="columnContents"></div></div></div>';
			this.s.add("#"+id);
			$(function(){$(a.jQDajareCloudGrid).append(s);});
		},
		createContent:function(ct){
			var a=this.s,b=a.get(),c=ct,s=b[ct[1]],st=s.replace("#","");
			a[st+"ColumnTitleText"] = s+" .columnTitle .columnTitleText",a[st+"ColumnTitleTextH3"] = a[st+"ColumnTitleText"]+" h3",a[st+"ColumnDescription"] = s+" .columnDescription",a[st+"ColumnContents"] = a[st+"ColumnDescription"]+" .columnContents";
			$(function(){
				$(a[st+"ColumnTitleTextH3"]).html(c[2].title);
			});
		},
		get:{$this:this,find:function(param){var v=window.jQDajareCloudValue,d={url:v.api.find, dataType:"jsonp", success:param.success, error:this.errorCallback};$.ajax(d);},errorCallback:function(){alert('Json Error!!');}},
		post:{}
	}
})(jQuery, window);

